package cn.com.dashihui.web.service;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.web.common.SysConfig;
import cn.com.dashihui.web.dao.User;

public class QuartzService {

	private static Logger logger = Logger.getLogger(QuartzService.class);
	/**
	 * 团购结束的业务
	 * 获取百分比
	 * 获取订单价格
	 * 获取更该用户积分  并记录
	 * @param good
	 */
	public void groupBuyOver(int id){
		//抵扣券
		Double gjkpoint = 0.00;
		//积分
		Double gsppoint = 0.00;
		try {
			gjkpoint = SysConfig.getGroupDownGiveD();
			gsppoint = SysConfig.getGroupDownGiveJ();
		} catch (Exception e) {
			logger.error("获取配制参数有误，团购结束券币赠送失败");
		}
		//找出已支付   未免单  的
		String sql = "SELECT * FROM t_bus_order_gb WHERE payState=? AND isFree=? AND goodsid=?";
		
		List<Record> find = Db.find(sql,2,0,id);
		if ( find!=null && find.size()>0 ){
			Double njkpoint = gjkpoint;
			Double nsppoint = gsppoint;
			find.stream().forEach(order->{
				//送积分补偿
				giveUserCompensation(njkpoint, nsppoint, order);
			});
		}
		
		
	}
	/**
	 * 团购结束用户补偿
	 * @param njkpoint  需要补偿的抵扣券百分比
	 * @param nsppoint	需要补偿的积分百分比
	 * @param order	订单
	 */
	private  void giveUserCompensation(Double njkpoint, Double nsppoint, Record order) {
		int userid = order.getInt("userid");
		User user = User.me().findById(userid);
		Double ojkpoint = user.getDouble("jkpoint");
		Double osppoint = user.getDouble("sppoint");
		Double amount = order.getDouble("amount");
		//需要变化的券值
		Double jkpoint = DoubleKit.mul(amount, njkpoint);
		Double sppoint = DoubleKit.mul(amount, nsppoint);
		Double nowjkpoint = DoubleKit.add(jkpoint, ojkpoint);
		Double nowsppoint = DoubleKit.add(sppoint, osppoint);
		String sqll = "UPDATE t_bus_user SET sppoint=? , jkpoint=? WHERE id=? AND sppoint=? AND jkpoint=? ";
		if ( Db.update(sqll,nowsppoint,nowjkpoint,userid,osppoint,ojkpoint)!=1 ){
			giveUserCompensation(njkpoint, nsppoint, order);
		}
		Record record = new Record();
		record.set("type", 1)
			  .set("flag", 14)
			  .set("fromOrderNum", order.getStr("orderNum"))
			  .set("orderMoney", amount)
			  .set("userid", userid)
			  .set("sppoint", sppoint)
			  .set("sppointHistory", sppoint)
			  .set("dedu",jkpoint)
			  .set("deduHistory",ojkpoint)
			  .set("describe", "团购结束未免单补偿")
			  .set("createDate", new Date());
		if ( !Db.save("t_bus_user_value_log", record) ){
			logger.error("团购结束送积分业务：用户积分变化记录失败=》"+record);
		}
	}
	
}
